<template>
  <div class="quotaDefine">
    <el-card class="container" style="height: 100%">
      <el-row>
        <el-col :span="7" style="margin-right: 15px">
          <div
            class="grid-content quotatree"
            style="border: 1px solid #dfe4ed; text-align: center; height: 550px"
          >
            <QuotaTree
              @dragNode="handleDragNode"
              class="quoTree"
              :showcheckbox="false"
              @computedQuota="computedQuota"
            />
          </div>
        </el-col>
        <el-col :span="16" style="height: 100%">
          <div class="grid-content bg-purple-light" style="height: 100%">
            <el-tabs v-model="activeName" type="card">
              <el-tab-pane label="指标公式" name="first">
                <el-row>
                  <el-col :span="11">
                    <div>
                      <div style="padding: 20px">
                        <div>运算符</div>
                        <div>
                          <draggable
                            style="display: inline-block"
                            v-for="item in operatorList"
                            :key="item.id"
                            :list="operatorList"
                            @end="handleEnd(item)"
                          >
                            <el-tag
                              @click.native="getOperator(item)"
                              style="margin: 5px"
                              type="info"
                              >{{ item.name }}
                            </el-tag>
                          </draggable>
                        </div>
                        <div class="Operator" @drop="drop" @dragover.prevent>
                          <draggable
                            :value="computedData"
                            @input="handleListChange($event)"
                          >
                            <el-dropdown
                              v-for="item in computedData"
                              :key="item.id"
                              trigger="click"
                            >
                              <el-tag                         
                                class="el-dropdown-link"
                                style="margin: 5px"
                                >{{ item.name }}
                                <i
                                  class="el-icon-arrow-down el-icon--right"
                                ></i>
                              </el-tag>
                              <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item
                                  @click.native="handleClose(item)"
                                  >删除</el-dropdown-item
                                >
                              </el-dropdown-menu>
                            </el-dropdown>
                          </draggable>
                        </div>
                        <!-- <div>
                          <div style="margin-top: 40px">指标共有维度</div>
                          <div class="contain">
                            <el-checkbox
                              v-for="item in commonDimensionList"
                              :key="item.rootId"
                              v-model="checked1"
                            >
                              {{ item.rootName }}
                            </el-checkbox>
                          </div>
                        </div> -->
                        <div style="margin: 20px 0">
                          <el-select
                            style="margin-right: 10px"
                            v-model="quotaFrom.typeId"
                            placeholder="请选择"
                          >
                            <el-option
                              v-for="item in computedType"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            >
                            </el-option>
                          </el-select>
                        </div>
                        <el-button @click="submitOperator" type="primary"
                          >生成新指标
                        </el-button>
                        <el-button @click="handleReset" type="primary"
                          >重置
                        </el-button>
                        <el-dialog
                          center
                          title="生成新指标"
                          :visible.sync="dialogVisible"
                          :close-on-click-modal="false"
                          :close-on-press-escape="false"
                          :show-close="false"
                          width="30%"
                        >
                          <div>
                            <el-form
                              ref="quotaFrom"
                              :model="quotaFrom"
                              :rules="quotaRules"
                            >
                              <el-form-item label="预指标名称" prop="name">
                                <el-input v-model="quotaFrom.name"></el-input>
                              </el-form-item>
                              <el-form-item label="预指标简称" prop="uname">
                                <el-input v-model="quotaFrom.uname"></el-input>
                              </el-form-item>
                              <el-form-item
                                label="预指标描述"
                                prop="description"
                              >
                                <el-input
                                  v-model="quotaFrom.description"
                                ></el-input>
                              </el-form-item>
                              <el-form-item label="预指标代码" prop="code">
                                <el-input v-model="quotaFrom.code"></el-input>
                              </el-form-item>
                              <el-form-item label="预指标标签" prop="lable">
                                <el-input v-model="quotaFrom.lable"></el-input>
                              </el-form-item>
                              <el-form-item label="根维度" prop="rootNode">
                                <el-input
                                  disabled
                                  v-model="quotaFrom.rootNodeName.join('  ')"
                                ></el-input>
                              </el-form-item>
                              <el-form-item label="关联维度" prop="rootNode">
                                <el-input
                                  disabled
                                  v-model="
                                    quotaFrom.childrenNodeName.join('  ')
                                  "
                                ></el-input>
                              </el-form-item>
                              <el-form-item
                                label="所属主题"
                                prop="themeSetId"
                                v-model="quotaFrom.themeSetId"
                              >
                                <el-radio-group
                                  size="small"
                                  v-for="item in themeSetList"
                                  :key="item.id"
                                  v-model="quotaFrom.themeSetId"
                                >
                                  <el-radio border :label="item.id"
                                    >{{ item.setTitle }}
                                  </el-radio>
                                </el-radio-group>
                              </el-form-item>
                              <el-form-item label="指标类型" prop="type">
                                <el-select
                                  v-model="quotaFrom.type"
                                  placeholder="请选择预指标类型"
                                >
                                  <el-option
                                    v-for="item in quotaType"
                                    :key="item.label"
                                    :label="item.value"
                                    :value="item.label"
                                  ></el-option>
                                </el-select>
                              </el-form-item>
                            </el-form>
                          </div>
                          <span slot="footer" class="dialog-footer">
                            <el-button @click="handleDialog(false)"
                              >取 消</el-button
                            >
                            <el-button
                              type="primary"
                              @click="handleDialog(true)"
                              >确 定</el-button
                            >
                          </span>
                        </el-dialog>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="12" style="padding: 20px 20px 0 70px">
                    <div
                      style="
                        height: 470px;
                        text-align: center;
                        overflow: auto;
                        border: 1px solid #d8dce5;
                      "
                    >
                      <div
                        class="commomDim"
                        style="
                          height: 32px;
                          line-height: 32px;
                          text-align: center;
                          border: 1px solid #d8dce5;
                        "
                      >
                        共有维度
                      </div>
                      <div class="common">
                        <el-tree
                          show-checkbox
                          node-key="id"
                          ref="dimTree"
                          :data="commonDimensionList"
                          :props="dimTreeProps"
                        ></el-tree>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script>
import QuotaTree from "@/views/quota/modeling/QuotaTree.vue";
import { getBeMixedTree } from "@/api/quota/define/define.js";
import {
  getDatasource,
  getTableAliasEnable,
  getColAlias,
  getAllFormulaOperator,
  queryQuotaType,
  quotaGenerateQuota,
  createQuotaByType,
  queryComputeType,
} from "@/api/quota/define/define.js";
import { getThemeSetByQuotaId } from "@/api/quota/theme_zone/set.js";
import draggable from "vuedraggable";

export default {
  components: { draggable, QuotaTree },
  data() {
    return {
      //计算类型
      computedType: [],
      dimTreeProps: {
        children: "children",
        label: "dimensionName",
      },
      checked1: true,
      dialogVisible: false,
      //当前拖拽运算符
      currentOperator: undefined,
      //当前选中节点
      selectColumn: undefined,
      //公共维度
      commonDimensionList: [],
      //运算符数据
      operatorList: [],
      //公式数据
      computedData: [],
      SqueryParams: {
        pageNum: 1,
        pageSize: 10,
        orderField: "UPDATE_DATE",
        order: "desc",
        tablenameAliasId: "",
      },
      themeSetList: [],
      quotaRules: {
        description: [
          { required: true, message: "请输入预指标描述", trigger: "blur" },
        ],
        lable: [
          { required: true, message: "请输入预指标标签", trigger: "blur" },
        ],
        themeSetId: [
          { required: true, message: "请选择所属主题", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入预指标名称", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择预指标类型", trigger: "blur" },
        ],
        uname: [
          { required: true, message: "请输入预指标简称", trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入预指标代码", trigger: "blur" },
        ],
      },
      quotaFrom: {
        typeId: "0",
        dimMap: {},
        themeTitle: null,
        description: null,
        lable: null,
        name: "",
        type: null,
        stype: "5",
        uname: null,
        code: null,
        themeSetId: null,
        parentId: 0,
        createType: 3,
        rootNodeName: [],
        childrenNodeName: [],
        quotaFormulaList: [],
        formula: "",
        dimIntMap: {},
      },
      quotaType: [],
      //字段弹窗数据
      fieldData: [],
      multipleSelection: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      dataBaseList: [],
      confirmSlot: undefined,
      selectValue: "",
      datasource: [],
      tableData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderField: "UPDATE_DATE",
        order: "desc",
        datasourceId: undefined,
        keyword: undefined,
      },
      activeName: "first",
    };
  },
  computed: {
    slDimensionList() {
      //序列化解决watch监听新旧值一样问题
      return JSON.stringify(this.dimensionList);
    },
  },
  watch: {
    computedData: {
      handler(newVal, oldVal) {
        let result = newVal.filter((item) => {
          return item.formulaType == 0;
        });
        if (result.length > 0) {
          let quotaIds = [];
          result.forEach((item) => {
            if (item.formulaType === 0) {
              quotaIds.push(item.id);
            }
          });
          getBeMixedTree(quotaIds).then((res) => {
            this.commonDimensionList = this.handleTree(
              res.data,
              "id",
              "upperId"
            );
          });
        } else {
          this.commonDimensionList = [];
        }
      },
      deep: true,
    },
  },
  created() {
    //获取计算类型
    queryComputeType().then((res) => {
      this.computedType = res.data;
    });
    //获取指标类型
    queryQuotaType().then((res) => {
      this.quotaType = res.data;
      console.log("this.quotaType");
      console.log(this.quotaType);
    });
    this.getDatasourceList();
    //加载所有的公式数据
    getAllFormulaOperator().then((res) => {
      this.operatorList = res.data;
      this.operatorList.forEach((item) => {
        item.name = item.operator;
      });
    });
  },
  methods: {
    //获取运算符
    getOperator(val) {
      val.formulaType = 1;
      this.computedData.push(val);
    },
    //获取指标节点生成公式
    computedQuota(val) {
      console.log("点击的数据:", val);
      val.formulaType = 0;
      this.computedData.push(val);
    },
    //拖拽改变数组元素的位置
    handleListChange(event) {
      this.computedData = event;
    },
    //Dialog框处理
    handleDialog(val) {
      if (!val) {
        this.dialogVisible = false;
        this.reset();
        return;
      }
      this.$refs["quotaFrom"].validate((valid) => {
        if (valid) {
          this.$confirm("提交后不可修改，确定提交吗？", "提示", {
            cancelButtonText: "取消",
            confirmButtonText: "确定",
            type: "warning",
          })
            .then(() => {
              console.log("quotaFrom", this.quotaFrom);
              this.quotaFrom.dimIntMap = this.quotaFrom.dimMap;
              createQuotaByType(this.quotaFrom).then((res) => {
                if (res.data) {
                  this.reset();
                  this.dialogVisible = false;
                  this.$message({
                    message: "数据已提交",
                    type: "success",
                  });
                }
              });
            })
            .catch(() => {
              this.reset();
              this.dialogVisible = false;
            });
        }
      });
    },
    //拖拽运算符
    handleEnd(val) {
      val.formulaType = 1;
      this.computedData.push(val);
    },
    drop(event) {
      // 判断drop的来源是否为树，与表头的drag/drop事件做区分
      if (this.selectColumn) {
        this.selectColumn.formulaType = 0;
        this.computedData.push(this.selectColumn);
        this.selectColumn = undefined;
      }
    },
    //拖拽树节点
    handleDragNode(data) {
      if (data.isQuota) {
        this.selectColumn = data;
      }
    },
    handleClose(tag) {
      this.$confirm("确定删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let index = this.computedData.findIndex((item) => {
            return tag.id === item.id;
          });
          this.computedData.splice(index, 1);
          // if(tag.isQuota) {
          //   let newArr = this.dimensionList.filter(
          //   (item) => {return item.quotaId !== tag.id}
          // )
          // this.dimensionList = newArr
          // }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //提交公式
    submitOperator() {
      if (this.computedData.length > 0) {
        let checkNode = this.$refs.dimTree.getCheckedNodes();
        if (checkNode.length <= 0) {
          this.$message({
            message: "请选择维度",
            type: "warning",
          });
          return;
        }
        let quotaIds = [];
        this.computedData.forEach((item) => {
          item.formulaTextId = item.id;
          this.quotaFrom.quotaFormulaList.push(item);
          this.quotaFrom.formula = `${this.quotaFrom.formula}${item.name}`;
          if (item.formulaType === 0) {
            quotaIds.push(item.id);
            this.quotaFrom.name = `${this.quotaFrom.name}  ${item.name}`;
          }
        });
        checkNode.forEach((item) => {
          if (item.upperId == 0) {
            //等于0为根节点
            this.quotaFrom.rootNodeName.push(item.dimensionName);
          } else {
            //子节点封装dimMap请求参数
            this.quotaFrom.childrenNodeName.push(item.dimensionName);
            this.quotaFrom.dimMap[item.id] = item.upperId;
          }
        });
        getThemeSetByQuotaId(quotaIds)
          .then((res) => {
            this.themeSetList = res.data;
            this.dialogVisible = true;
          })
          .catch(() => {
            return;
          });
      } else {
        this.$message({
          message: "没有相应的指标公式数据可提交",
          type: "warning",
        });
      }
    },
    reset() {
      this.computedData = [];
      this.commonDimensionList = [];
      this.tempDimensionList = [];
      this.dimensionList = [];
      this.themeSetList = [];
      this.quotaFrom = {
        dimMap: {},
        themeTitle: null,
        description: null,
        lable: null,
        name: "",
        type: null,
        stype: "5",
        uname: null,
        code: null,
        themeSetId: null,
        parentId: 0,
        createType: 3,
        rootNodeName: [],
        childrenNodeName: [],
        quotaFormulaList: [],
        formula: "",
        dimIntMap: {},
      };
    },
    handleReset() {
      this.computedData = [];
      this.commonDimensionList = [];
      this.tempDimensionList = [];
      this.dimensionList = [];
      this.themeSetList = [];
      this.quotaFrom.name = "";
    },
    //提交选中字段
    submitSelectValue() {},
    //选中字段
    handleSelectionChange() {},
    //选择字段
    selectField(val) {
      this.dialogTableVisible = true;
      this.queryParams.tablenameAliasId = val.id;
      getColAlias(this.queryParams).then((res) => {
        this.fieldData = res.data;
      });
    },
    //选中数据库表
    handleCurrentChange(val) {
      if (!val) {
        return;
      }
      this.dataBaseList.push(val);
    },
    //选中的值
    selectChange(val) {
      this.queryParams.datasourceId = val;
      this.getTableAliasList();
    },
    //加载表别名数据
    getTableAliasList() {
      if (this.queryParams.datasourceId == undefined) {
        this.msgError("请先选择数据源");
      } else {
        getTableAliasEnable(this.queryParams).then((res) => {
          this.tableData = res.data;
        });
      }
    },
    //加载数据源数据
    getDatasourceList() {
      getDatasource().then((res) => {
        this.datasource = res.data;
      });
    },
    onSubmit() {},
  },
};
</script>
<style lang="less">

.common {
  overflow: auto;
  text-align: left;

  .el-tree__empty-text {
    display: none;
  }
}

.el-form-item {
  margin-bottom: 0;
}

.quotaDefine {
  .el-tabs__header {
    margin: 0;
  }
  .el-icon-arrow-down{
    visibility: hidden;
  }
  .el-dropdown-link:hover .el-icon-arrow-down {
    visibility: visible;
  }
  .contain {
    width: 100%;
    height: 135px;
    border: 1px solid #dfe4ed;
    margin-top: 10px;
  }

  .el-tree {
    display: inline-block;
  }

  .quotatree {
    overflow: auto;
  }

  .quoTree {
    text-align: left;
  }

  .Operator {
    width: 100%;
    height: 285px;
    border: 1px solid #dfe4ed;
    margin-top: 10px;
  }

  .el-tag {
    display: inline-block;
  }

  .dbtable {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 150px;
    height: 60px;
    background-color: #cbeaff;
    border-radius: 5px;
    text-align: center;
    padding-top: 10px;
  }

  .el-tabs {
    height: 509px;
  }

  .el-tabs__content {
    border: 1px solid #dfe4ed;
    height: 100%;
  }
}
</style>
